<template>
	<view>
		<uni-popup ref="speci" type="center" zindex border-radius="16rpx 16rpx 0 0" @maskClick="maskClick">
			<view class="pu_content">
				<view class="pucon_c">
					<view class="pucon_c_t text-xxl text-c3">
						{{spcData.vname}}<text class="margin-left-xs text-xl"
							v-if="spcData.kcal>0">{{spcData.kcal}}Kcal</text>
					</view>
					<view class="menu_introduce" v-if="spcData.vintroduction">
						{{spcData.vintroduction}}
					</view>
					<block v-for="(fitem,findex) in spcData.list" :key="findex">
						<view class="separate">
							<view class="separate_line"></view>
							<view class="separate_text">{{fitem.name}}</view>
						</view>
						<view class="gg_box margin-top-sm flex">
							<view v-if="fitem.subList" class="sepList-item text-lg p_rlt"
								v-for="(item, index) in fitem.subList" :key="index"
								:class="fitem.selecId==item.id?'checkUn':'uncur'" @click="tapItem(item,fitem)">
								<view v-if="item.isSellOut == '1' && cartStore.curOrderType.type == ''" class="ycmbox text-acenter text-df text-white">已售罄</view>
								<view class="sepCuname"
									:style="{color:item.isSellOut=='1'&&cartStore.curOrderType.type==''?'#666':'#000'}">
									{{item.vname}}</view>
								<view class="spcPrice" v-if="item.spcPriceShow"><text
										class="fcon-Vector1 spcPrice_icons"></text></view>
							</view>
						</view>
					</block>
				</view>
				<view class="btns flex align-center">
					<view class="f_pri">
            <!-- props.isReplace -->
            <text v-if="props.isReplace">+</text>
						<text class="text-lg">¥</text><text class="spcPriFont">{{ spcData.showPrice != null ? spcData.showPrice : spcData.price}}</text>
						<text class="pri_reduce">¥{{spcData.priceReduce}}</text>
					</view>
					<view class="f_sub text-lg" @click="doSubmit" ref="button-r0">加入购物车</view>
				</view>
				<text class="cuIcon-roundclose"
					style="color: #fff;font-size: 80rpx;margin-left: 310rpx;font-weight: 200;" @click="close"></text>
			</view>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted } from 'vue';
	import { useShopStore } from '@/stores/shopStore';
	import { useCartStore } from '@/stores/cartStore';
	import { queryLabelListByGoodsIdn } from '@/api/vmeitime-http/index.js'
	import mapi from '@/utils/mapi';
	const store = useShopStore();
	const cartStore = useCartStore();
	const emit = defineEmits(["maskClick", "submit"])
	const speci = ref()
	const propsE = ref()
	const goodsItem = ref<any>({})
	// const cdata = ref()
	// const imgBaseUrl = ref("https://cdn-static.yekjx.com/food/images/")
	const spcData = ref<any>({
		vname: "",
		kcal: "463",
		price: 0,
		list: [],
		isVip: 0
	})
  const props = defineProps({
  	isReplace: {
  		type: Number,
  		default: null,
  	}
  });
	onMounted(() => {
		// cdata.value = props.data
	})
	const setPrice = (item) => {
		spcData.value.priceReduce = item.activity ? (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price) : item.old_price;
		spcData.value.price = item.activity ? item.activity_price : (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price);
    if(props.isReplace){
    	spcData.value.showPrice = props.isReplace < spcData.value.price?(transQsPrice(spcData.value.price - props.isReplace)):0;
      console.log('替换商品--------',spcData.value.price,props.isReplace)
    }
	};
  const transQsPrice=(num:any)=>{
  	 if (Number.isInteger(num)) {
  	    return num; // 如果是整数，直接返回
  	  } else {
  	    return num.toFixed(2); // 否则，保留两位小数
  	  }
  }
	const open = (v : any, e : any) => {
		console.log(v, "store.cartInfo")
		goodsItem.value = v;
		spcData.value.list = [];
		propsE.value = e || '';
		spcData.value.vname = v.name;
		spcData.value.kcal = v.energy || '';
		spcData.value.isVip = v.isVip;
		spcData.value.specialId = v.specialId || '';
		spcData.value.shopType = v.shopType;
		spcData.value.priceReduce = v.activity ? (store.costPlan == '1130' ? v.site_sell_price : v.out_sell_price) : v.old_price;
		spcData.value.price = v.activity ? v.activity_price : (store.costPlan == '1130' ? v.site_sell_price : v.out_sell_price);
		spcData.value.pageSource = v.pageSource;
		spcData.value.vmaster_product_image_id = v.vmaster_product_image_id;
		spcData.value.vintroduction = v.vintroduction;
		spcData.value.parentOneId = v.parentOneId||'';
		spcData.value.vtwo_type=v.vtwo_type||''
		let spcMergedData = {}
		cartStore.cartList && cartStore.cartList.forEach((item : any) => {
			if (spcMergedData[item.sku]) {
				spcMergedData[item.sku].num += item.num;
			} else {
				spcMergedData[item.sku] = { num: item.num, sku: item.sku };
			}
		})
		let resultSpc : any = Object.values(spcMergedData);
		v.specList?.forEach((item : any) => {
			const nindexs = resultSpc.findIndex((resItems : any) => item.sku == resItems.sku);
			item.num = nindexs >= 0 ? resultSpc[nindexs].num : 0;
		});

		let gg : any = {
			name: "规格",
			selecId: '',
			subList: [],
			flags: "mains"
		}
		gg.selecId = v.specList[0].sku
		for (let item of v.specList) {
			gg.subList.push(
				{
					...item,
					id: item.sku,
					spcPriceShow: (item.activity && item.activityType == '243') ? true : false,
					isSellOut: item.nsell_nums<=0 ? '1' : '0'
					// isSellOut: item.num >= item.nsell_nums ? '1' : '0'
				})
		}
		// for (let item of v.specList) {
		//     const itemNum = item.num ?? 0;
		//     if (spcData.value.pageSource == 'tejia') {
		//         if (item.activity && item.activityType == '243' && itemNum < item.nsell_nums) {
		//             gg.selecId = item.sku;
		// 						spcData.value.priceReduce=item.activity ? (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price) : item.old_price
		// 						spcData.value.price=item.activity ? item.activity_price : (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price)
		//             break;
		//         }
		//     } else {
		//         if (cartStore.curOrderType.type == 'SUBSCRIBE') {
		//             gg.selecId = item.is_default_buy == '5' ? item.sku : '';
		// 						spcData.value.priceReduce=item.activity ? (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price) : item.old_price
		// 						spcData.value.price=item.activity ? item.activity_price : (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price)
		//             break;
		//         } else {
		//             if (item.is_default_buy == '5' && itemNum < item.nsell_nums) {
		// 								spcData.value.priceReduce=item.activity ? (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price) : item.old_price
		// 								spcData.value.price=item.activity ? item.activity_price : (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price)
		//                 gg.selecId = item.sku;
		//                 break;
		//             } else if (itemNum < item.nsell_nums) {
		//                 gg.selecId = item.sku;
		// 								spcData.value.priceReduce=item.activity ? (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price) : item.old_price
		// 								spcData.value.price=item.activity ? item.activity_price : (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price)
		//             }
		//         }
		//     }
		// }
		for (let item of v.specList) {
			const itemNum = item.num ?? 0;
			if (spcData.value.pageSource == 'tejia') {
				if (item.activity && item.activityType == '243' && itemNum < item.nsell_nums) {
					gg.selecId = item.sku;
					setPrice(item);
					break;
				}
			} else {
				if (cartStore.curOrderType.type == 'SUBSCRIBE') {
					if(item.is_default_buy == '5'){
						gg.selecId=item.sku 
						 break;
					}
					// gg.selecId = item.is_default_buy == '5' ? item.sku : '';
					setPrice(item);
				} else {
					if (item.is_default_buy == '5' && itemNum < item.nsell_nums) {
						gg.selecId = item.sku;
						setPrice(item);
						break;
					} else if (itemNum < item.nsell_nums) {
						gg.selecId = item.sku;
						setPrice(item);
					}
				}
			}
		}
		spcData.value.list.push(gg)
		getOtherSpc(v.goods_id)
		// speci.value.open()
	}
	
	const getOtherSpc = async (goodsId : any) => {
		try {
			let res = await queryLabelListByGoodsIdn({ goodsId: goodsId })
			speci.value.open()
			if (!res.result) {
				return
			}
			let ggList = res.object.map((item : any) => {
				return {
					name: item.labelType,
					selecId: '',
					flags: "orts",
					subList: item.labelList.map((label : any) => {
						return {
							...label,
							id: label.label_id,
							vname: label.name
						};
					})
				};
			});
			spcData.value.list = [...spcData.value.list, ...ggList]
		} catch (e) {
		}

	}
	const maskClick = (e : any) => {
		emit("maskClick")
	}
	const doSubmit = () => {
		let result = spcData.value.list[0].subList.find((item) => item.sku === spcData.value.list[0].selecId);
		let labelsIds = spcData.value.list.filter(item => item.flags !== "mains").map(item => item.selecId).filter(selecId => selecId !== "");
		result.labelIds = labelsIds;
		result.name = spcData.value.vname;
		result.isVip = spcData.value.isVip;
		result.specialId = spcData.value.specialId;
		result.shopType = spcData.value.shopType;
		result.vmaster_product_image_id = spcData.value.vmaster_product_image_id;
		result.parentOneId = spcData.value.parentOneId;
		result.vtwo_type=spcData.value.vtwo_type
		close()//暂
		let params : any = {
			result: result,
			goodsItem:goodsItem.value
		}
		if (propsE.value) {
			params.e = { events: propsE.value }
		}
		uni.vibrateShort();
		emit("submit", params)
	}
	const tapItem = (item : any, fitem : any) => {
		if (item.isSellOut == '1' && cartStore.curOrderType.type == '') {
			mapi.msg("该规格已售罄！")
			return
		}
		if (fitem.flags == 'mains') {
			spcData.value.price = item.activity ? item.activity_price : (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price)
			spcData.value.priceReduce = item.activity ? (store.costPlan == '1130' ? item.site_sell_price : item.out_sell_price) : item.old_price
			spcData.value.kcal = item.energy || ''
      if(props.isReplace){
      	spcData.value.showPrice = props.isReplace < spcData.value.price?(transQsPrice(spcData.value.price - props.isReplace)):0;
        console.log('替换商品--------',spcData.value.price,props.isReplace)
      }
		}
		fitem.selecId = item.id
	}

	const close = () => {
		emit("maskClick")
		speci.value.close()
	}
	defineExpose({ open, close })
</script>

<style lang="scss" scoped>
	.pu_content {
		width: 700rpx;

		.pucon_c {
			background-color: #fff;
			border-radius: 20rpx 20rpx 0rpx 0rpx;
			max-height: 62vh;
			overflow-y: scroll;
			padding: 20rpx 20rpx 20rpx 30rpx;

			.pucon_c_t {
				// position: sticky;
				// left:0;
				// top:0;
				// background-color: #fff;
				// line-height: 50rpx;
			}

			.menu_introduce {
				width: 99%;
				min-height: 40rpx;
				border-radius: 10rpx;
				background: rgba(235, 239, 251, 0.50);
				padding: 20rpx 0rpx 20rpx 20rpx;
				color: #333;
				font-size: 32rpx;
				margin: 20rpx auto;
			}

			.separate {
				width: 90%;
				height: 40rpx;
				display: flex;
				padding-left: 5rpx;
				margin-top: 40rpx;

				.separate_line {
					width: 8rpx;
					height: 35rpx;
					background-color: #53A87F;
				}

				.separate_text {
					margin-left: 17rpx;
					color: #333;
					font-size: 32rpx;
					font-weight: 700;
					height: 35rpx;
					line-height: 35rpx;
				}
			}
		}

		.gg_box {
			min-height: 30rpx;
			flex-wrap: wrap;

			.sepList-item {
				position: relative;
				width: auto;
				height: 90rpx;
				border-radius: 120rpx;
				background: #F7F7F7;
				margin-left: 10rpx;
				margin-top: 20rpx;
				text-align: center;
				line-height: 90rpx;
				color: #333;
				padding: 0rpx 20rpx 0rpx 20rpx;
				overflow: hidden;

				.sepCuname {
					min-width: 100rpx;
				}

				.spcPrice {
					position: absolute;
					right: 5rpx;
					top: -2rpx;
					width: 68rpx;
					height: 26rpx;
					border-radius: 0px 120px 0px 200rpx;
					background: linear-gradient(90deg, #FF7A00 -10.89%, #FCDCBF 138.82%);
					color: #fff;
					display: flex;
					justify-content: center;
					align-items: center;

					.spcPrice_icons {
						font-size: 14rpx;
						margin-top: 1rpx;
					}
				}
			}

			.checkUn {
				border: 2rpx solid #53A87F;
				background-color: #F1FBF1;
			}

			.uncur {
				border: 2rpx solid #F7F7F7;
			}
		}
	}
	.ycmbox{
		width: 100%;
		border-radius: 90rpx;
		height: 90rpx;
		background: rgba(0, 0, 0, 0.50);
		position: absolute;
		z-index:1;
		left: 0;
		top: 0;
	}
	.btns {
		width: 100%;
		height: 136rpx;
		border-radius: 0rpx 0rpx 20rpx 20rpx;
		border-top: 2rpx solid #F7F7F7;
		justify-content: space-between;
		padding: 20rpx 20rpx 0rpx 20rpx;
		background-color: #fff;

		.f_pri {
			line-height: 120rpx;
			font-size: 48rpx;
			color: #FC4C40;
			margin-left: 10rpx;
			font-weight: 700;
		}

		.f_sub {
			width: 260rpx;
			height: 80rpx;
			border-radius: 10rpx;
			background: #53A87F;
			color: #fff;
			text-align: center;
			line-height: 80rpx;
			letter-spacing: 2rpx;
			margin-right: 10rpx;
			font-weight: 700;
		}

	}

	.ballshow {
		width: 100%;
		height: 100rpx;
		border: 1px solid red;
		margin-top: 100rpx;
	}

	.pri_reduce {
		text-decoration: line-through;
		color: #999;
		font-size: 28rpx;
		margin-left: 15rpx;
	}

	.spcPriFont {
		font-size: 72rpx;
	}
</style>